<template></template>

<script>
export default {
  props: {},
  data() {
    return {
      socket: null,
      messages: [],
    };
  },
  created() {},
  mounted() {
    this.initWebSocket();
  },
  beforeDestroy() {
    this.closeWebSocket();
  },
  methods: {
    initWebSocket() {
      // 创建 WebSocket 连接
      this.socket = new WebSocket('ws://192.168.1.111:8090/user/topic/identity-changed');

      // 监听连接打开事件
      this.socket.addEventListener('open', (event) => {
        console.log('WebSocket connection opened:', event);
      });

      // 监听消息事件
      this.socket.addEventListener('message', (event) => {
        console.log('Message from server:', event.data);
        this.messages.push(event.data); // 更新数据
      });

      // 监听错误事件
      this.socket.addEventListener('error', (event) => {
        console.error('WebSocket error observed:', event);
      });

      // 监听关闭事件
      this.socket.addEventListener('close', (event) => {
        console.log('WebSocket is closed now.');
      });
    },
    sendMessage(message) {
      if (this.socket && this.socket.readyState === WebSocket.OPEN) {
        this.socket.send(JSON.stringify(message));
      }
    },
    closeWebSocket() {
      if (this.socket) {
        this.socket.close();
      }
    },
  },
};
</script>

<style lang="less" scoped></style>
